import { save } from "../utils/Storage";
import { request } from "../utils/request";
import { flow } from 'mobx';

class UserStore {
  userInfo: any;

  // 登录方法
  // requestLogin = async (phone: string, pwd: string, callback: (success: boolean) => void) => {
  //   try {
  //     const params = {
  //       name: phone,
  //       pwd: pwd,
  //     };
  //     const { data } = await request('login', params);
  //     if (data) {
  //       this.userInfo = data;
  //       callback?.(true);
  //     } else {
  //       this.userInfo = null;
  //       callback?.(false);
  //     }
  //   } catch (error) {
  //     console.log(error);
  //     this.userInfo = null;
  //     callback?.(false);
  //   }
  // };


  // mobx 改装的登录
  requestLogin = flow(function* (
    this: UserStore,
    phone: string,
    pwd: string,
    callback: (success: boolean) => void) {
    try {
      const params = {
        name: phone,
        pwd: pwd,
      };
      const { data } = yield request('login', params);
      if (data) {
        save('userInfo', JSON.stringify(data));
        this.userInfo = data;
        callback?.(true);
      } else {
        this.userInfo = null;
        callback?.(false);
      }
    } catch (error) {
      console.log(error);
      this.userInfo = null;
      callback?.(false);
    } finally {
    }
  })



}

// ESM单例导出
export default new UserStore();